package com.common.library.data;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.concurrent.TimeoutException;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;

import com.zs4sdk.common.Extra;
import com.common.library.entity.JSONResultEntity;
import com.common.library.util.ActivityHelper;
import com.common.library.util.Helper;
import com.common.library.util.JsonHelper;
import com.common.library.util.LogUtil;
import com.common.library.util.NetworkHelper;

public abstract class CommonEventHandler {
	
	private static final String TAG = CommonEventHandler.class.getSimpleName();
	
	// JSON的编码前缀
	String mEncodePrefix = Extra.EVENTHANDLEINFO.PREFIX_ENCODE_JSON_STRING;
	
	// 随机字符串长度
	int mRandomStringLength = Extra.EVENTHANDLEINFO.LENGTH_RANDOM_STRING;
	
	String url;
	ArrayList<NameValuePair> params;
	String useragent1;

	ResultHandlerInEvent resultHandler;
	
	/**
	 * 通信请求是否要解密，默认要
	 */
	boolean isEncrypt = true;
	
	
	public void execRequest() {
		
		// 提交数据
		new Thread() {
			
			@Override
			public void run() {
				super.run();
				
				JSONObject result = null;
				HttpResponse response = null;
				String responseStr = null;
				
				try {
					
					try {
						response = doRequest();
					} 
					catch (Exception e) {
						e.printStackTrace();
						LogUtil.e(TAG, "error msg" + e.getMessage());
						
						result = getErrorJson(e);
					}
					
					if (Helper.isNotNull(response) && NetworkHelper.isHttpResponseSuccess(response)){
						responseStr = NetworkHelper.getHttpResponseString(response);
						result = getResultJson(responseStr);
//						Log.e("result+===",result.toString());
					}
					// 网络请求错误jsonresult
					else {
						result = createSendFailJSON(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_http_request_fail")));
					}
					
					if (Helper.isNull(result)){
						result = createSendFailJSON(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_http_request_fail")));
					}
					
//					LogUtil.i(TAG, "result: " + result);
					resultHandler.doResultHanler(result);
					
				} catch (Exception e) {
					
					sendMessage(Extra.MessageKey.EVENT_EXCEPTION, e);
					
					e.printStackTrace();
				} 
			}
		}.start();
	}
	
	
	
	/**
	 * 
	 * function: 得到有错误信息的json
	 *
	 * @param e
	 * @return
	 * 
	 * @ author: aXiBa 2013-3-14 下午5:33:53
	 */
	private JSONObject getErrorJson(Exception e) {
		
		// 请求超时
		if(e instanceof TimeoutException || e instanceof ConnectTimeoutException || e instanceof SocketTimeoutException) {
			return createSendFailJSON(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_http_request_timeout")));
		}
		// 请求错误
		else {
			return createSendFailJSON(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_http_request_fail")));
		}
	}
	
	
	// 创建错误json
	public static JSONObject createSendFailJSON(String msg){
		JSONResultEntity entity = new JSONResultEntity(
				Extra.JSONReturnResult.FAIL
				, msg);
		return entity.toJSON();
	}
	
	/**
	 * 
	 * function: 
	 *
	 * @param responseStr
	 * @return
	 * 
	 * @ author: aXiBa 2013-3-14 上午9:55:29
	 */
	private JSONObject getResultJson(String responseStr) {

		JSONObject result = null;
		
		// 不需要解密返回
		if(!isEncrypt) {
			try{
				result = new JSONObject(responseStr);
			}catch (Exception e) {
				e.printStackTrace();
				result = createSendFailJSON(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_http_request_fail")));
			}
		}
		// 需要解密
		else {
			result = JsonHelper.simpleJsonDecode(mEncodePrefix, mRandomStringLength, responseStr);
			if (Helper.isNull(result)){
				result = createSendFailJSON(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_http_request_fail")));
			}
		}
		
		return result;
	}
	
	
	/**
	 * CommonActivity里的handler
	 */
	Handler eventHandler = new Handler() {
		
		public void handleMessage(Message msg) {
			
			// 异常
			if(Extra.MessageKey.EVENT_EXCEPTION == msg.what) {		
				resultHandler.doExceptionHandler();
			}
		};
	};
	
	
	/**
	 * 
	 * function: 
	 *
	 * 
	 * @ author: aXiBa 2011-5-4 下午12:52:25
	 */
	public void sendMessage(int what, Object param) {
		
		Message msg = eventHandler.obtainMessage();
		msg.what = what;
		
		if(null != param) {
			msg.obj = param;
		}
		eventHandler.sendMessage(msg);
	}
	
	
	// 需要被重写的接口
	public abstract HttpResponse doRequest() throws Exception;
	
	
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 实现处理
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	public interface ResultHandlerInEvent {
	
		// 成功处理
		void doResultHanler(JSONObject result) throws JSONException;
		
		void doExceptionHandler();
	
	}
	
}
